﻿// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Metadata.Edm;

namespace EdmMetadataHelpers
{
    /// <summary>
    /// A class containing extension methods for Edm Metadata classes
    /// </summary>
    public static class MetadataItemExtensions
    {
        /// <summary>
        /// Gives us the ability to store extra information against MetadataItem(s) by name
        /// </summary>
        private static Dictionary<MetadataItem, Dictionary<string, object>> _extensions = new Dictionary<MetadataItem, Dictionary<string, object>>();

        public static Dictionary<string, object> GetExtendedProperties(this MetadataItem obj)
        {
            if (!_extensions.Keys.Contains(obj))
                _extensions.Add(obj, new Dictionary<string, object>());
            return _extensions[obj];
        }
        /// <summary>
        /// Makes it easy to see for a particular EdmProperty whether it is also 
        /// a key.
        /// <remarks>
        /// This method caches it's results, so if asked a second time
        /// no enumeration of DeclaringType KeyMembers is necessary
        /// </remarks>
        /// </summary>
        public static bool IsEntityKey(this EdmProperty property)
        {
            Dictionary<string, object> extensions = property.GetExtendedProperties();
            if (!extensions.ContainsKey("IsEntityKey"))
            {
                extensions["IsEntityKey"] = GetIsEntityKey(property);
            }
            return (bool)extensions["IsEntityKey"];
        }
        /// <summary>
        /// Works out whether an EdmProperty is being used as part of it's DeclaringType's key
        /// </summary>
        /// <param name="property">The property to check</param>
        /// <returns>If the property is a key</returns>
        internal static bool GetIsEntityKey(EdmProperty property)
        {
            bool IsEntityKey = false;
            EntityType et = property.DeclaringType as EntityType;
            if (et != null)
                IsEntityKey = et.KeyMembers.Any(km => km.Name == property.Name);
            return IsEntityKey;
        }
    }
}
